﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.impl;
using DLL;
using Newtonsoft.Json;

namespace BLL
{
    public class TradSend
    {
        // 数据库地址
        string sqlType;
        string sqlAddress;
        string sqlSelcet;
        string sqlSqlSort;
        long sqlSize;
        public TradSend(string sqlType,string sqlAddress,string sqlSelcet,string sqlSqlSort,long sqlSize)
        {
            this.sqlType = sqlType;
            this.sqlAddress = sqlAddress;
            this.sqlSelcet = sqlSelcet;
            this.sqlSqlSort = sqlSqlSort;
            this.sqlSize = sqlSize;
        }

        public String findSendData() {
            try
            {
                ITradData tradData = this.tradData();
                DataTable dataTable = tradData.getTreadList(sqlAddress, sqlWhere());
                return JsonConvert.SerializeObject(dataTable);
            }
            catch (Exception ex) {
                return ex.Message;   
            }
        }
        /// <summary>
        /// SQL Server  SqlLit  MySql  Oracle Access
        /// </summary>
        /// <returns></returns>
        private String sqlWhere () {
            StringBuilder sqlHead = new StringBuilder();
            sqlHead.Append("SELECT "); 
            switch (sqlType) {
                case "Access":
                case "SQL Server":
                    sqlHead.Append(" TOP ").Append(sqlSize).Append(" ").Append(sqlSelcet);
                    break;
                case "SqlLit":
                case "MySql":
                case "Oracle":
                    sqlHead.Append(sqlSelcet);
                    break;
                default:
                    sqlHead.Append(sqlSelcet);
                    break;
            }
            sqlHead.Append(" ORDER BY ").Append(sqlSqlSort).Append(" DESC");
            if (sqlType != "Access" && sqlType != "SQL Server")
            {
                sqlHead.Append(" LIMIT ").Append(sqlSize);
            }
            return sqlHead.ToString();
        }

        private ITradData tradData() {
            ITradData tradData;
            switch (sqlType)
            {
                case "Access":
                    tradData = new TradDataAccess();
                    break;
                case "SQL Server":
                    tradData = new TradDataSQLServer();
                    break;
                case "SqlLit":
                    tradData = new TradDataSqlLit();
                    break;
                case "MySql":
                    tradData = new TradDataMySql();
                    break;
                case "Oracle":
                    tradData = new TradDataOracle();
                    break;
                default:
                    tradData = new TradDataAccess();
                    break;
            }
            return tradData;
        }
    }
}
